package com.oceanstar.controller;

import com.oceanstar.Pojo.*;
import com.oceanstar.service.IDiseaseStatsService;
import com.oceanstar.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/stats/disease")
@CrossOrigin(origins = "*")
public class DiseaseStatsController {

    @Autowired
    private IDiseaseStatsService diseaseStatsService;

    @GetMapping("/summary")
    public Result getDiseaseSummary(
            @RequestParam(required = false) String begin,
            @RequestParam(required = false) String end,
            @RequestParam(required = false) Integer gridId,
            @RequestParam(required = false) Integer gender,
            @RequestParam(required = false) Integer minAge,
            @RequestParam(required = false) Integer maxAge,
            @RequestParam(required = false) String diseaseNames,
            @RequestHeader("token") String token) {

        try {
            Claims claims = JwtUtils.parseToken(token);
            Integer identity = (Integer) claims.get("identity");
            if (identity != 3 && identity != 4) {
                return Result.error("权限不足");
            }

            DiseaseStatsQuery query = new DiseaseStatsQuery();
            query.setBegin(begin);
            query.setEnd(end);
            query.setGridId(gridId);
            query.setGender(gender);
            query.setMinAge(minAge);
            query.setMaxAge(maxAge);
            query.setDiseaseNames(diseaseNames);

            DiseaseSummaryDTO summary = diseaseStatsService.getDiseaseSummary(query);
            return Result.success(summary);
        } catch (Exception e) {
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    @GetMapping("/heatmap")
    public Result getDiseaseHeatmap(
            @RequestParam(required = false) String begin,
            @RequestParam(required = false) String end,
            @RequestParam(defaultValue = "community") String level,
            @RequestParam(required = false) Integer gridId,
            @RequestParam(defaultValue = "rate") String metric,
            @RequestHeader("token") String token) {

        try {
            Claims claims = JwtUtils.parseToken(token);
            Integer identity = (Integer) claims.get("identity");
            if (identity != 3 && identity != 4) {
                return Result.error("权限不足");
            }

            DiseaseHeatmapQuery query = new DiseaseHeatmapQuery();
            query.setBegin(begin);
            query.setEnd(end);
            query.setLevel(level);
            query.setGridId(gridId);
            query.setMetric(metric);

            DiseaseHeatmapDTO heatmap = diseaseStatsService.getDiseaseHeatmap(query);
            return Result.success(heatmap);
        } catch (Exception e) {
            return Result.error("查询失败: " + e.getMessage());
        }
    }
}